<?php
namespace Swork\Handler;

use Swork\Bean\Holder\InstanceHolder;
use Swork\Configer;
use Swork\Helper\ArrayHelper;
use Swork\Helper\TcpHelper;
use Swork\Server\Connection;
use Swork\Server\Tcp\TcpHandlerInterface;
use Swork\Service;

/**
 * TCP处理器
 * Class TcpHandler
 * @package Swork\Handler
 */
class TcpHandler implements TcpHandlerInterface
{
    /**
     * @var string
     */
    private $uri = '';

    /**
     * @var string
     */
    private $body = '';

    /**
     * @var bool
     */
    private $break = false;

    /**
     * 获取路径
     * @return string
     */
    public function getUri()
    {
        return $this->uri;
    }

    /**
     * 获取内容
     * @return string
     */
    public function getBody()
    {
        return $this->body;
    }

    /**
     * 设置截断
     */
    public function setBreak()
    {
        $this->break = true;
    }

    /**
     * 是否截断
     * @return bool
     */
    public function isBreak()
    {
        return $this->break;
    }

    /**
     * TCP Receive
     * @param \swoole_server $server
     * @param $fd
     * @param $from_id
     * @param $data
     */
    public function onReceive(\swoole_server $server, $fd, $from_id, $data)
    {
        //提取命令内容
        $rel = TcpHelper::getContent($data);
        if ($rel == false)
        {
            $this->break = true;
            return;
        }

        //获取命令合集
        $cmds = Configer::get('tcp');
        if (!is_array($cmds) || !isset($cmds[$rel[0]]))
        {
            $this->break = true;
            return;
        }

        //解析命令
        $this->uri = $cmds[$rel[0]];

        //解析内容
        if (isset($rel[1]))
        {
            $this->body = $rel[1];
        }
    }

    /**
     * 监听 onclose
     * @param \swoole_server $server
     * @param int $fd
     */
    public function onClose(\swoole_server $server, int $fd)
    {
        //找到连接描述符
        $info = Connection::get($fd);
        if ($info == false)
        {
            return;
        }

        //找到连接的类
        $cls = $info['onClose'] ?? false;
        if ($cls == false)
        {
            return;
        }
        if (substr($cls, 0, 1) != '\\')
        {
            $cls = '\\' . $cls;
        }

        //实例化
        $ins = InstanceHolder::getClass($cls);
        if ($ins == false)
        {
            return;
        }

        //执行调用
        $ins->onClose($fd);
    }
}
